package protomsg

import (
	"strings"

	"gitee.com/night-tc/gobige/common"
)

// BaseData 基础仓库数据

// Clone 复制一个BaseData
func (this BaseData) Clone() *BaseData {
	result := new(BaseData)
	result.Data = make(map[int64]int64)
	for k, v := range this.Data {
		result.Data[k] = v
	}
	return result
}

// NewBaseDataString 用字符串初始化一个数据
func NewBaseDataString(str string) *BaseData {
	result := new(BaseData)
	result.Data = make(map[int64]int64)
	if str == "" || str == "0" {
		return result
	}
	arr := StringToArray(str, ";")
	for i := 0; i < len(arr); i += 2 {
		result.Data[arr[i]] = arr[i+1]
	}
	return result
}

// UpData 更新指定数据
func (this *BaseData) UpData(key, num int64) {
	v := this.Data[key]
	if num+v > 0 {
		this.Data[key] = v + num
	} else {
		delete(this.Data, key)
	}
}

// UpDataBc批量用别的数据，更新本数据
func (this *BaseData) UpDataBc(addbc, delbc *BaseData) {
	if delbc != nil {
		for k, n := range delbc.Data {
			this.UpData(k, -n)
		}
	}
	if addbc != nil {
		for k, n := range addbc.Data {
			this.UpData(k, n)
		}
	}
}

// GetNumByKey指定数据的值
func (this *BaseData) GetNumByKey(key int64) int64 {
	v, ok := this.Data[key]
	if !ok {
		return 0
	}
	return v
}

// ToString 字符串化
func (this *BaseData) ToString() string {
	sb := common.NewStringBuilder()
	t := 0
	for k, v := range this.Data {
		if t == 0 {
			t++
		} else {
			sb.Append(";")
		}
		sb.AppendInt(int(k))
		sb.Append(";")
		sb.AppendInt(int(v))
	}
	return sb.ToString()
}

// Count 总数量
func (this *BaseData) Count() (result int64) {
	for _, n := range this.Data {
		result += n
	}
	return result
}

// MaxItem 最大数值的KEY，value
func (this *BaseData) MaxItem() (key, num int64) {
	for k, n := range this.Data {
		if n > num {
			key, num = k, n
		}
	}
	return key, num
}

// Clear清数据
func (this *BaseData) Clear() {
	this.Data = make(map[int64]int64)
}

// --------------------------------------------
func StringToArray(str string, sub string) []int64 {
	if str == "0" || str == "" {
		return make([]int64, 0)
	}
	str = strings.ReplaceAll(str, " ", "")
	arr := strings.Split(str, sub)
	result := make([]int64, len(arr))
	for i, v := range arr {
		tmp, _ := common.NewString(v).ToInt()
		result[i] = int64(tmp)
	}
	return result
}
